﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using EHR.Common;
using System.Windows.Data;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;
using CommunitySystem.Ctrls;

namespace CommunitySystem.PageView.公务员选拔
{
    public partial class ExamePublishWindow : ChildWindow
    {
        private CommunitySystem.PublicOfficialSelectionService.PublicOfficialSelectionServiceClient client = null;
        private CommunitySystem.Model.Silverlight.PublicOfficialInfo entity = null;
        private int errorCount = 0;
        public ExamePublishWindow(int id)
        {
            InitializeComponent();
            client = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
            client.ChechIsPublishCompleted += new EventHandler<PublicOfficialSelectionService.ChechIsPublishCompletedEventArgs>(client_ChechIsPublishCompleted);
            client.SavePublicOfficialInfoCompleted += new EventHandler<PublicOfficialSelectionService.SavePublicOfficialInfoCompletedEventArgs>(client_SavePublicOfficialInfoCompleted);
            client.UploadFileCompleted += new EventHandler<PublicOfficialSelectionService.UploadFileCompletedEventArgs>(client_UploadFileCompleted);
            client.UploadStringCompleted += new EventHandler<PublicOfficialSelectionService.UploadStringCompletedEventArgs>(client_UploadStringCompleted);
            this.BindingValidationError += (sender, e) =>
            {
                if (e.Action == ValidationErrorEventAction.Added)
                {
                    errorCount++;
                }
                else if (e.Action == ValidationErrorEventAction.Removed)
                {
                    errorCount--;
                }
            };
            client.GetPublicOfficialInfoCompleted += new EventHandler<PublicOfficialSelectionService.GetPublicOfficialInfoCompletedEventArgs>(client_GetPublicOfficialInfoCompleted);
            if (id > 0)
            {
                client.GetPublicOfficialInfoAsync("id = " + id);
            }
            else
            {
                entity = new Model.Silverlight.PublicOfficialInfo() { InputName = Session.LoginUser.LoginName };
                this.DataContext = entity;
                SetExameType(entity);
            }
        }

        void client_UploadStringCompleted(object sender, PublicOfficialSelectionService.UploadStringCompletedEventArgs e)
        {
            UploadFileInfo info = e.UserState as UploadFileInfo;
            if (info.UploadString.Count == 0)
            {
                client.SavePublicOfficialInfoAsync(_entity, listfiles, info.Name);
            }
            else
            {
                client.UploadStringAsync(info.Name, info.UploadString[0], false, info);
                info.UploadString.RemoveAt(0);
            }
        }

        void client_SavePublicOfficialInfoCompleted(object sender, PublicOfficialSelectionService.SavePublicOfficialInfoCompletedEventArgs e)
        {
            if (e.Result)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功");
                this.DialogResult = true;
            }
            else
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("保存失败");
            }
        }

        private CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo serviceEntity = null;
        void client_GetPublicOfficialInfoCompleted(object sender, PublicOfficialSelectionService.GetPublicOfficialInfoCompletedEventArgs e)
        {
            serviceEntity = e.Result.FirstOrDefault();
            _orgs = serviceEntity.Orgs;
            if (serviceEntity != null)
            {
                entity = CommunitySystem.Model.Silverlight.EntityConvertor.Convert<Model.Silverlight.PublicOfficialInfo>(serviceEntity);
                this.DataContext = entity;
                SetExameType(entity);
                client.GetFilesCompleted += (sender1, e1) =>
                {
                    if (e1.Result.Count > 0)
                    {
                        foreach (var c in e1.Result)
                        {
                            UploadFileInfo upf = new UploadFileInfo() { FilesID = c.ID, DisplayName = c.Displayname, Name = c.filename };
                            _files.Add(upf);
                            addFileToUI(upf);
                        }
                    }
                };
                client.GetFilesAsync(entity.ID);
               
            }
        }

        private void SetExameType(Model.Silverlight.PublicOfficialInfo info)
        {
            int type = info.Type;
            switch (type)
            {
                case 0: rb0.IsChecked = true;
                    break;
                case 1: rb1.IsChecked = true;
                    break;
            }
            if (!string.IsNullOrEmpty(info.Infomation))
                rtb.SetXaml(info.Infomation);
           
        }

        private ObservableCollection<CommunitySystem.PublicOfficialSelectionService.ExameOrg> _orgs = null;
        private void GetExameType(Model.Silverlight.PublicOfficialInfo info)
        {
            if (rb0.IsChecked == true)
            {
                info.Type = 0;
               
            }
            else if (rb1.IsChecked == true)
            {
                info.Type = 1;
            }
            info.Infomation = rtb.GetXaml();
        }
        private UploadFileInfo _Xaml = null;
        private bool NeedToUpload = false;
        private int lenght = 2500;
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            NeedToUpload = false;
            tags.Clear();
            listfiles.Clear();
            BindingExpression beUsername = tbName.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            //int count = Validation.GetErrors().Count;
            if (errorCount > 0)//判断是否有验证失败
                return;
            GetExameType(entity);
            entity.Status = 1;
            //entity.InputTime = DateTime.Now;
            //client.SavePublicOfficialInfoAsync(CommunitySystem.Model.Silverlight.EntityConvertor.Convert
            //    <CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo>(entity));
            entity.InputTime = DateTime.Now;
            _entity = CommunitySystem.Model.Silverlight.EntityConvertor.Convert
                <CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo>(entity);
            _entity.Orgs = _orgs;


            //if (_entity.Infomation.Length > lenght)
            //{
            //    _Xaml = new UploadFileInfo() { status = 2, Name = Guid.NewGuid().ToString("N"), Size = lenght };
            //    NeedToUpload = true;
            //    byte[] content = new byte[lenght];
            //    int position = 0;
            //    while (position < _entity.Infomation.Length)
            //    {
            //        if (position + lenght > _entity.Infomation.Length)
            //            lenght = _entity.Infomation.Length - position;
            //        _Xaml.UploadString.Add(_entity.Infomation.Substring(position, lenght));
            //        position += lenght;
            //    }
            //    _entity.Infomation = string.Empty;
            //}


            //验证是有已有考试处于发布状态
            client.ChechIsPublishAsync(_entity.ID);

        }

        void client_ChechIsPublishCompleted(object sender, PublicOfficialSelectionService.ChechIsPublishCompletedEventArgs e)
        {
            if (e.Result == false)
            {
                foreach (var f in _files)
                {
                    CommunitySystem.PublicOfficialSelectionService.Files _f = new PublicOfficialSelectionService.Files() { Displayname = f.DisplayName, InputDate = DateTime.Now, filename = f.Name, ID = f.FilesID, ParentTableKey = entity.ID };
                    if (f.Context != null && f.Context.Count > 0)
                    {
                        client.UploadFileAsync("file", f.Name, f.Context[0], true, f);
                        f.Context.RemoveAt(0);
                        tags.Add(f, false);
                    }
                    listfiles.Add(_f);
                }
                if (tags.Count == 0)
                {
                    if (NeedToUpload == true)
                    {
                        client.UploadStringAsync(_Xaml.Name, _Xaml.UploadString[0], true, _Xaml);
                        _Xaml.UploadString.RemoveAt(0);
                    }
                    else
                    {
                        client.SavePublicOfficialInfoAsync(_entity, listfiles, "");
                    }
                }
            }
            else
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("已有考试处于发布状态，不能发布，请先锁定已发布考试");
            }
            
        }

       

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo _entity = null;

        private Dictionary<UploadFileInfo, bool> tags = new Dictionary<UploadFileInfo, bool>();
        private ObservableCollection<CommunitySystem.PublicOfficialSelectionService.Files> listfiles = new ObservableCollection<PublicOfficialSelectionService.Files>();
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            NeedToUpload = false;
            tags.Clear();
            listfiles.Clear();
            BindingExpression beUsername = tbName.GetBindingExpression(TextBox.TextProperty);
            beUsername.UpdateSource();
            //int count = Validation.GetErrors().Count;
            if (errorCount > 0)//判断是否有验证失败
                return;
            GetExameType(entity);
            entity.Status = 0;
            entity.InputTime = DateTime.Now;
            _entity = CommunitySystem.Model.Silverlight.EntityConvertor.Convert
                <CommunitySystem.PublicOfficialSelectionService.PublicOfficialInfo>(entity);
            _entity.Orgs = _orgs;

            //if (_entity.Infomation.Length > lenght)
            //{
            //    _Xaml = new UploadFileInfo() { status = 2, Name = Guid.NewGuid().ToString("N"), Size = lenght };
            //    NeedToUpload = true;
            //    byte[] content = new byte[lenght];
            //    int position = 0;
            //    while (position < _entity.Infomation.Length)
            //    {
            //        if (position + lenght > _entity.Infomation.Length)
            //            lenght = _entity.Infomation.Length - position;
            //        _Xaml.UploadString.Add(_entity.Infomation.Substring(position, lenght));
            //        position += lenght;
            //    }
            //    _entity.Infomation = string.Empty;
            //}

            foreach (var f in _files)
            {
                CommunitySystem.PublicOfficialSelectionService.Files _f = new PublicOfficialSelectionService.Files() { Displayname = f.DisplayName, InputDate = DateTime.Now, filename = f.Name, ID = f.FilesID, ParentTableKey = entity.ID };
                //if (_entity.Files == null)
                //    _entity.Files = new ObservableCollection<PublicOfficialSelectionService.Files>();
                //_entity.Files.Add(_f);
                if ( f.Context != null &&f.Context.Count > 0)
                {
                    client.UploadFileAsync("file", f.Name, f.Context[0], true, f);
                    f.Context.RemoveAt(0);
                    tags.Add(f, false);
                }
                listfiles.Add(_f);
            }
            if (tags.Count == 0)
            {
                if (NeedToUpload == true)
                {
                    client.UploadStringAsync(_Xaml.Name, _Xaml.UploadString[0], true, _Xaml);
                    _Xaml.UploadString.RemoveAt(0);
                }
                else
                {
                    client.SavePublicOfficialInfoAsync(_entity, listfiles, "");
                }
                //client.SavePublicOfficialInfoAsync(_entity, listfiles);
            }
            //client.SavePublicOfficialInfoAsync(_entity);
            
        }

        void client_UploadFileCompleted(object sender, PublicOfficialSelectionService.UploadFileCompletedEventArgs e)
        {
            UploadFileInfo f = e.UserState as UploadFileInfo;

            if (f.Context.Count == 0)
            {
                tags[f] = true;
                int count = tags.Values.Where(c => c == false).Count();
                if (count == 0)
                {
                    
                    if (NeedToUpload == true)
                    {
                        client.UploadStringAsync(_Xaml.Name, _Xaml.UploadString[0], false, _Xaml);
                        _Xaml.UploadString.RemoveAt(0);
                    }
                    else
                    {
                        client.SavePublicOfficialInfoAsync(_entity, listfiles, "");
                    }
                    return;
                }
            }
            else
            {
                client.UploadFileAsync("file", f.Name, f.Context[0], false, f);
                f.Context.RemoveAt(0);
            }




        }
        
        private ObservableCollection<UploadFileInfo> _files = new ObservableCollection<UploadFileInfo>();

        private void HyperlinkButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {

            var filesDialog = new OpenFileDialog() { Multiselect = false };

            if (filesDialog.ShowDialog() == false)
                return;

            //var s = files.FullName;

            // 文件内容
            System.IO.Stream stream = filesDialog.File.OpenRead();



            UploadFileInfo uploadFile = new UploadFileInfo() { DisplayName = filesDialog.File.Name, Name = Guid.NewGuid().ToString() };
            uploadFile.Size = stream.Length / 1024.00;
            uploadFile.Context = new List<byte[]>();
            int b = 0;
           
            while (stream.Position > -1 && stream.Position < stream.Length)
            {
                if (stream.Length - stream.Position >= 16000)
                {
                    b = 16000;
                }
                else
                {
                    b = (int)(stream.Length - stream.Position);
                }

                byte[] filebyte = new byte[b];
                stream.Read(filebyte, 0, b);
                uploadFile.Context.Add(filebyte);
            }
            stream.Close();
            if (uploadFile.Context.Count > 0)
            {
                _files.Add(uploadFile);
                addFileToUI(uploadFile);
            }
            
           
        }

        private void addFileToUI(UploadFileInfo uploadFile)
        {
            Border border = new Border() { BorderThickness = new Thickness(1, 1, 1, 1), BorderBrush = new SolidColorBrush(Colors.Red), Margin = new Thickness(5, 2, 0, 0) };
            StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };
            TextBlock tb = new TextBlock() { Text = uploadFile.DisplayName, Margin = new Thickness(5, 0, 0, 0) };
            sp.Children.Add(tb);
            HyperlinkButton hlb = new HyperlinkButton() { Content = "×", Margin = new Thickness(2, 0, 0, 0), Foreground = new SolidColorBrush(Colors.Red), Tag = border, Name = uploadFile.Name };
            hlb.Click += new RoutedEventHandler(hlb_Click);
            sp.Children.Add(hlb);
            border.Child = sp;
            wp.Children.Add(border);
            //读取指定大小的文件流内容到uploadFile.Context以便上传
           
           
        }

        void hlb_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton hlb = sender as HyperlinkButton;
            Border b = hlb.Tag as Border;
            if (b != null)
                wp.Children.Remove(b);
            string name = hlb.Name;
            _files.Remove(_files.Where(c => c.Name == name).FirstOrDefault());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click2(object sender, System.Windows.RoutedEventArgs e)
        {
        	// 在此处添加事件处理程序实现。
            OrgSelectWindow window = new OrgSelectWindow(_orgs);
            window.Show();
            window.Closed -= new EventHandler(window_Closed);
            window.Closed += new EventHandler(window_Closed);
			
        }

        void window_Closed(object sender, EventArgs e)
        {
            OrgSelectWindow window = sender as OrgSelectWindow;
            if (window.DialogResult == true)
            {
                _orgs = window._orgs;
            }
        }

       

        private void ModelRadioButton_Click(object sender, RoutedEventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            if (rb != null)
            {
                switch (rb.Name)
                {
                    case "edit":
                        rtb.EditorStatus = Beetle.Sl.EditorControl.Core.EditorStatusEnum.Edit;
                        break;
                    case "design":
                        rtb.EditorStatus = Beetle.Sl.EditorControl.Core.EditorStatusEnum.Designer;
                        break;
                    case "preView":
                        var content = rtb.GetZipBytes();
                        RTBPreViewWindow win = new RTBPreViewWindow(content);
                        win.Show();
                        break;
                }
            }
        }
    }
}

